//模块主窗口
var Role = Role||{} ;
Role.RoleManagerPanel = Ext.extend(Ext.Panel,{
	 closable: true,
   	 autoScroll:true,
   	 layout:'border',
   	 width:'100%',
   	 initComponent : function() {
   			var gd = new Role.RoleGridPanel({region : "center"}) ;
   			this.tbar =  this.buildBbar(this) ;
   			this.items = [gd] ;
			this.formPanel =  new Ext.Window({
	   			layout:"border",
	   			title: "添加角色",
	   			closeAction: 'hide',
				resizable:false,
				modal:true,
				width:550,
				height:300,
				items :[new Role.RoleForm({gridPanel:gd}) ]
   			});
			
   		Role.RoleManagerPanel.superclass.initComponent.call(this);
   	},
   	addRole : function(btn) {
   		 var tform = btn.ownerCt.ownerCt.formPanel;  	
   		 var form = tform.items.get(0).getForm();
   		 form.reset();
   	     tform.show();
   	},
   	deleteRole: function(btn) {
   		var gp = btn.ownerCt.ownerCt.items.get(0) ;
   		var rows= gp.getSelectionModel().getSelections(); 
   		if(rows.length==0) {
   			 Ext.Msg.alert("提示", "请选择需要删除的角色~");
   			 return ;
   		}
   		var ids = "";
   		for(var i=0 ;i<rows.length;i++) {
   			if(i==0) {
   				ids = rows[i].data['id'] ;
   			}else{
   				ids = ids +","+rows[i].data['id'] ;
   			}
   		}
   		Ext.MessageBox.confirm("确认", "确认要删除所选中的角色吗?", function(btn) {
					if (btn == "yes") {
						 Ext.Ajax.request( {
							 waitMsg : '正在执行  ',
							 method : 'POST',
							 params : {
								ids:ids 
							 },
							 url : 'action.php?action=role&method=deleteRole',
							 scope : this,
							 success : function(request) {
								var Result=Ext.decode(request.responseText);
								if(Result.success) {
									gp.getStore().reload();
								} else {
									 Ext.Msg.alert("错误",Result.info );
								}
							 },
							 failure : function() {
								Ext.Msg.alert("错误", "与后台联系的时候出现了问题");
							 }
						 });
					}
				});
   		
   	},
   	buildBbar: function(mp) {
   		return [{
   				text: "添加角色",
   				handler:this.addRole,
   				iconCls: 'ico-task-add'
   			},'-',{
   				text: "删除角色",
   				handler:this.deleteRole,
   				iconCls: 'ico-task-delete'
   			},'-',{
   				text: "分配权限",
   				handler:this.giveQx,
   				execType:1,
   				iconCls: 'ico-task-hf_06'
   			},'-',{
   				text: "删除权限",
   				handler:this.giveQx,
   				execType:2,
   				iconCls: 'ico-task-edit'
   			},'-',{
   				text: "编辑角色",
   				handler:this.execInfo,
   				iconCls: 'ico-task-edit'
   			},'->',{
            		xtype:'textfield',
   				    width:200,
   				    ref: '../searchText',
   				    emptyText:'输入角色名称查询',
   				    name:'roleName',
   				    listeners:{
	                 'specialkey':function(f,e) {
	                 	 if(e.getKey() == e.ENTER){
	                 	 		var doSearch = mp.doSearch ;
	                 	 		mp.queryRoleList(doSearch);               		 
	                 	 }
	                 }
   				}
	            },{
	   				text : "查询",
	   				iconCls: 'ico-dot-search',
	   				ref:'../doSearch',
	   				handler :this.queryRoleList
	            }] ;
   	},queryRoleList:function(btn){
   		var tp =  btn.ownerCt.ownerCt ;
   		var gp = tp.items.get(0);
   		gp.recordStart = 1;
   		var text = tp.searchText.getValue() ;
   		gp.store.baseParams = {
   			'tdRole.roleName' :text
   		} ;
   		gp.store.load({params:{start:0, limit:1000}});
   	},
   	giveQx : function(btn) {
   		 var execType = btn.execType ;
   		 var gp = btn.ownerCt.ownerCt.items.get(0) ;
   		 var rows= gp.getSelectionModel().getSelections(); 
   		 if(rows.length==0) {
   			 Ext.Msg.alert("提示", "请选择一个角色~");
   			 return ;
   		}
   		 var title ;
   		 if(execType==2)
   			 title = "为角色”"+rows[0].data['roleName']+"”删除权限";
   		 else
   		 	title = "为角色”"+rows[0].data['roleName']+"”分配权限";
   		 new Ext.Window({
	   			layout:"fit",
	   			title: title,
	   			closeAction: 'hide',
				resizable:false,
				modal:true,
				width:550,
				height:650,
				items :[new Ext.tree.TreePanel ({
						header :false,
					    split: true,
						rootVisible : false,
						autoScroll : true,
						loader : new Ext.tree.TreeLoader({
    							url : 'user_geAllPage.action?type=1&execType='+execType+'&roleId='+rows[0].data['roleId'],
    							root:'root'
    						}),	
    					root : new Ext.tree.AsyncTreeNode({
							id:'0',  
					        text: '所有权限' ,
					        leaf:true,
					        expended:true
						 }),
						 listeners : {
							checkchange:function(node) {
								if(node.attributes.checked && !node.leaf ) {
									node.expand(false,true,function(n){
										for(var i=0;i<n.childNodes.length;i++) {
											if(n.childNodes[i].leaf) {
												n.childNodes[i].getUI().checkbox.checked=true ;//=true;
												n.childNodes[i].attributes.checked =true;
											}
											
										}
									})
								}
								
								if(!node.attributes.checked && !node.leaf ) {
									node.expand(false,true,function(n){
										for(var i=0;i<n.childNodes.length;i++) {
											n.childNodes[i].getUI().checkbox.checked=false ;//=true;
											n.childNodes[i].attributes.checked =false;
										}
									})
								}
							}
						 },
						 buttonAlign :'center',
						 minButtonWidth:60,
						 buttons:[{
							text:"确定",
							handler : function(btn){
								var treePanel = this.ownerCt.ownerCt;
								var allCheck = treePanel.getChecked();
								var ids ;
								var role = rows[0] ;
								var postUrl ;
								if(execType==1) {
									postUrl = 'main_addRolePageRel.action';
								} else {
									postUrl = 'main_deleteRoleFunRel.action';
								}
								for(var i=0;i<allCheck.length;i++) {
									if(i==0) {
										ids = 	allCheck[i].id ;
									} else {
										ids = ids+","+allCheck[i].id ;
									}
								}
								Ext.Ajax.request({
				            	   method: 'POST',
				            	   params:{
				     					ids:ids,
				     					roleId:role.data['roleId']
				     					 },
				            	   url: postUrl,
				            	   success:function(request){
				            				btn.ownerCt.ownerCt.ownerCt.close();
				            	        },
				            	   failure:function(){
				                         Ext.Msg.alert("错误", "与后台联系的时候出现了问题");
				                        }  
				                   });
							}
						}, {
							text : '取消',
							handler : function() {this.ownerCt.ownerCt.ownerCt.hide();}
						}]
					 })]
   			}).show();
   	}
});

Role.RoleGridPanel = Ext.extend(Ext.grid.EditorGridPanel,{
	header: false,
	loadMask:{msg:'加载中...'},
	enableDragDrop: false,
	viewConfig :{
        forceFit: true
    },
	initComponent : function() {
       	var thisGrid = this;
       	this.recordStart = 1 ;
    	var userCm = new Ext.grid.CheckboxSelectionModel({
				dataIndex: "uid",
                sortable: false,
                singleSelect:false,
                width:20
		});
		var rn = new　Ext.grid.RowNumberer({
		　　header　:　"序号",
		　　width　:　35,
		　　renderer:function(value,metadata,record,rowIndex){
		　　　return　　thisGrid.recordStart　+　rowIndex;
		　　}
		});
		this.columns　=　[userCm,rn,　
		    {
				header:'角色标识',
				sortable:true,
				dataIndex:"id",
				width:70
			},{
		        header:'角色名称',
				sortable:true,
				dataIndex:"roleName",
				width:70
			},{
		        header:'角色描述',
				sortable:true,
				dataIndex:"remark",
				width:70
			},{
		        header:'生效时间',
				sortable:true,
				dataIndex:"startDay",
				width:70
			},{
		        header:'失效时间',
				sortable:true,
				dataIndex:"endDay",
				width:70
			},{
				header:'权限预览',
				sortable:true,
				dataIndex:"id",
				width:70,
				align :"center",
				renderer :function(value, metaData, record) {
					var name = record.data['roleName'] ;
					return '<input type="button" onclick="showQX('+value+',\''+name+'\');" value="查看权限"/>';
				}
			}
		] ;
		var dataStore = new Ext.data.JsonStore({
			url : 'action.php?action=role',
			root: 'root',
	        totalProperty: 'totalProperty',
	        fields: [
	           'id','roleName','remark','startDay','endDay'
	        ]
		});
	
		this.store = dataStore;
		this.sm = userCm;
		this.bbar = new Ext.PagingToolbar({
			pageSize : 25,
			store : dataStore,
			displayInfo : true,
			displayMsg : '第 {0} - {1} 条  共 {2} 条',
			emptyMsg : "没有记录",
			listeners:{
				beforechange:function(pt,obj) {
					thisGrid.recordStart = obj.start+1 ;
				    
				}
			}
		});
		dataStore.load({
			params:{
				start:0,
				limit:25
			}
		});
	Role.RoleGridPanel.superclass.initComponent.call(this);
	}
});


Role.RoleForm = Ext.extend(Ext.form.FormPanel,{
	layout:"form",
	region : "center",
	labelAlign:"right",
	width:550,
	height:300,
	frame:true,
	initComponent: function(){
	this.items=[{fieldLabel : '角色名称',
							name : 'roleName',
							xtype : 'textfield',
							allowBlank:false,
							anchor:"90%",
							maxLength:20,
							maxLengthText:"最大长度不能超过20个字符",
							minLength:2,
							minLengthText:"最少要2个字符"
						},
						{fieldLabel : '生效时间',
							name : 'startDay',
							xtype : 'datefield',
							allowBlank:false,
							anchor:"90%",
							format:"Y-m-d",
							validator:function(v) {
								var st = this.ownerCt.getForm().findField("endDay").getValue();
								if(v && st) {
									st = st.format("Y-m-d");
									return v<st?true:"生效时间必须小于失效时间";
								}
								return true;
							}
						},{fieldLabel : '失效时间',
							name : 'endDay',
							xtype : 'datefield',
							allowBlank:false,
							anchor:"90%",
							format:"Y-m-d",
							validator:function(v) {
								var st = this.ownerCt.getForm().findField("startDay").getValue();
								if(v && st) {
									st = st.format("Y-m-d");
									return v<st?"失效时间必须大于生效时间":true;
								}
								return true;
							}
						},{fieldLabel : '角色描述',
							name : 'remark',
							xtype : 'textarea',
							allowBlank:false,
							anchor:"90%",
							maxLength:50,
							maxLengthText:"最大长度不能超过50个字符",
							minLength:2,
							minLengthText:"最少要2个字符"
						},{ 
							name : 'id',
							xtype : 'textfield',
							hidden:true,
							anchor:"90%"
						},{
							boxLabel:"完成后自动关闭",
							name : 'isHiden',
							xtype : 'checkbox'
						}
		];
	  Role.RoleForm.superclass.initComponent.call(this);
	},
	buttonAlign :'center',
	minButtonWidth:60,
	buttons:[{
		text:"确定",
		handler : function(btn){
		     var thisForm = btn.ownerCt.ownerCt.getForm();
		     if(!thisForm.isValid()) {
		    	 return ;
		     }
		     var isHid = thisForm.findField("isHiden").getValue();
		     var store = btn.ownerCt.ownerCt.gridPanel.getStore() ;
			 thisForm.submit({
					waitTitle : '请稍候...',
					waitMsg : '正在提交表单数据,请稍候...',
					method : 'post',
					url:'action.php?action=role&method=addRole',
					success : function(form, action) {
						store.reload();
						if(isHid)
							btn.ownerCt.ownerCt.ownerCt.hide();
					}
		    });
		    //隐藏弹出页面
		}
	}, {
		text : '重置',
		handler : function() {this.ownerCt.ownerCt.form.reset();}
	}, {
		text : '取消',
		handler : function() {this.ownerCt.ownerCt.ownerCt.hide();}
	}]
});


